const CART_KEY = 'ONLINE_CART';

const state = {
    cart: localStorage.getItem(CART_KEY) ? JSON.parse(localStorage.getItem(CART_KEY)) : [],
    createOrderData: sessionStorage.getItem('createOrderData') ? JSON.parse(sessionStorage.getItem('createOrderData')) : {},
    createPayData: sessionStorage.getItem('createPayData') ? JSON.parse(sessionStorage.getItem('createPayData')) : {},
};

const getters = {
    createOrderData: state => state.createOrderData,
    createPayData: state => state.createPayData,
};

const mutations = {
    dataCreateOrder(state, data) {
        sessionStorage.setItem('createOrderData', JSON.stringify(data));
        state.createOrderData = JSON.parse(sessionStorage.getItem('createOrderData'));
    },
    dataCreatePay(state, data) {
        sessionStorage.setItem('createPayData', JSON.stringify(data));
        state.createPayData = JSON.parse(sessionStorage.getItem('createPayData'));
    },
    addToCart_online(state, cart) {
        state.cart = cart;
        updateCart(state.cart);
    }
};

const actions = {
    addToCart({state, commit}, SKU) {
        // console.log('state.cartList', state)
        let cartList = {};
        let cartNum = {};
        if (state.cart.cartList) {
            cartList = state.cart.cartList;
            cartNum = state.cart.cartNum;
        }
        let system = SKU.system;
        let gid = SKU.gid;
        let buyid = SKU.buyid;
        let count = SKU.count;
        if (!cartList[system]) {
            cartList[system] = {};
        }
        if (!cartNum[system]) {
            cartNum[system] = {};
            cartNum[system].cartNum = 0;
        }
        if (cartList[system][gid]) {
            if (!cartList[system][gid][buyid]) {
                cartList[system][gid][buyid] = {};
                cartList[system][gid][buyid] = {
                    "num": count,
                };
                cartNum[system].cartNum++;
            } else {
                cartList[system][gid][buyid].num = cartList[system][gid][buyid].num + count;
            }
        } else {
            cartList[system][gid] = {};
            cartList[system][gid][buyid] = {
                "num": count,
            };
            cartNum[system].cartNum++;
        }
        let cartData = {
            cartList: cartList,
            cartNum: cartNum,
        };
        commit('addToCart_online', cartData);
    }
};

export default {
    state,
    getters,
    actions,
    mutations
};

function updateCart(data) {
    localStorage.setItem(CART_KEY, JSON.stringify(data));
}
